﻿using GWB.Application.Common;
using GWB.Core.Enum;
using GWB.Core.TableEntity;
using GWB.Supplier;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace GWB.System.Api.Extensions
{
    /// <summary>
    ///初始化数据
    /// </summary>
    public static class DataInit
    {
        /// <summary>
        /// 菜单按钮初始化
        /// </summary>
        /// <param name="services"></param>
        public static void AddMenuButtonInit(this IServiceCollection services)
        {

            try
            {
                //清空按钮表
                //SqlSugarDb.Db.DbMaintenance.TruncateTable<MenuButton>();
                var actionListData = SqlSugarDb.Db.Queryable<Core.TableEntity.Action>().ToList();
                var types = Assembly.Load("GWB.Application").GetTypes().ToList();
                var calssName = "";
                foreach (var item in types)
                {
                    foreach (var attribute in Attribute.GetCustomAttributes(item, typeof(ApiExplorerSettingsAttribute)))
                    {
                        var attr = attribute.GetType();
                        if (attr.FullName != null && attr.FullName.Contains("ApiDescriptionSettingsAttribute"))
                        {
                            calssName = ((ApiDescriptionSettingsAttribute)attribute).Tag;
                        }
                    }
                    var methods = item.GetMethods();
                    foreach (var method in methods)
                    {

                        var methodAttribute = Attribute.GetCustomAttribute(method, typeof(AuthorizationAttribute));
                        if (methodAttribute == null) continue;
                        var attribute = methodAttribute as AuthorizationAttribute;
                        //插入按钮数据
                        InsertData(actionListData, item, method, attribute, calssName);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("出错了:" + e.ToString());
                if (e.ToString().Contains("Invalid object name"))
                {
                    SqlSugarDb.CodeFirst(new List<string>() { "Sys_Action" });
                }
            }

        }

        /// <summary>
        /// 插入数据
        /// </summary>
        public static void InsertData(List<Core.TableEntity.Action> actionListData, Type type, MethodInfo method, AuthorizationAttribute attribute, string calssName)
        {
            if (actionListData.Where(x => x.Name == attribute.Name
                                       && x.Namespace == type.FullName
                                       && x.ClassName == calssName
                                       && x.Code == attribute.Code.ToString()).Count() <= 0)
            {
                if (attribute == null) return;
                var controllerName = type.Name?.Replace("AppService","");
                var actionName = method.Name;
                var requestMode = GetRequestMode( ref actionName);

                SqlSugarDb.Db.Insertable(new Core.TableEntity.Action()
                {
                    Code = attribute.Code.ToString(),
                    Name = attribute.Name,
                    Namespace = type.FullName,
                    ClassName = calssName,
                    IsDeleted = false,
                    RequestMode = requestMode,
                    Route = $"/{controllerName}{actionName}"
                }).ExecuteCommand();
                Console.WriteLine(type.FullName + "添加按钮" + attribute.Name);
            }

        }

        /// <summary>
        /// 获取请求方式
        /// </summary>
        /// <param name="actionName"></param>
        /// <returns></returns>
        private static string GetRequestMode( ref string actionName)
        {
            var requestMode = "GET";
            var list = new List<string>() { "Add", "Delete", "Update", "Query", "Get", "Send", "Save", "Detail", "List" };

            foreach (var item in list)
            {
                //TODO:如果强制指定类型没有判断
                var index = actionName.ToLower().IndexOf(item.ToLower());
                if (index != 0) continue;
                actionName = item != actionName ? "/"+actionName.ToLower().Replace(item.ToLower(),"") : "";
                switch (item.ToLower())
                {
                    case "get":
                        requestMode = "GET";
                        break;
                    case "update":
                        requestMode = "PUT";
                        break;
                    case "delete":
                        requestMode = "DELETE";
                        break;
                    default:
                        requestMode = "POST";
                        break;
                }
            }

            return requestMode;
        }
    }
}
